package main

import (
	"fmt"
	"io"
	"net"
	"os"
)

func receiveFile(conn net.Conn, fileName string)  {
	f, err := os.Create(fileName)
	if err != nil {
		fmt.Println("os.Create err = ", err)
		return
	}
	defer f.Close()

	//读取接收的内容
	buf := make([]byte, 1024 * 4)
	for {
		n, err := conn.Read(buf)
		if err != nil {
			if err == io.EOF {
				fmt.Println("文件接收完毕")
			} else {
				fmt.Println("conn.Read err = ", err)
			}
			return
		}


		_, err = f.Write(buf[:n])
		if err != nil {
			fmt.Println("f Write err = ", err)
			return
		}
	}

}

func main() {

	//接收文件
	listener, err := net.Listen("tcp", "127.0.0.1:8000")
	if err != nil {
		fmt.Println("net Listen err = ", err)
		return
	}
	defer listener.Close()
	fmt.Println("等待接收文件中")

	//阻塞等待用户连接
	conn, err := listener.Accept()
	if err != nil {
		fmt.Println("Listener.Accept err = ", err)
		return
	}
	defer conn.Close()

	for {
		//接收文件名
		buf := make([]byte, 1024)
		n, err := conn.Read(buf)
		fileName := string(buf[:n])
		if err != nil {
			if err == io.EOF {
				fmt.Printf("文件[%s]接收完毕\n", fileName)
			} else {
				fmt.Println("conn.Read err = ", err)
				return
			}
		}
		fmt.Println("当前文件:", fileName)
		conn.Write([]byte("ok"))

		//接收文件内容
		receiveFile(conn, fileName)
	}

}
